package edu.gyc.hiblog.schedules;

import edu.gyc.hiblog.model.Post;
import edu.gyc.hiblog.service.PostService;
import edu.gyc.hiblog.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

@Component
public class ViewCountAsyTask {

    private static Logger logger = Logger.getLogger(ViewCountAsyTask.class.getName());

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    PostService postService;

//    @Scheduled(cron = "0 0/1 * * * *")  //每分钟同步
    @Scheduled(cron = "0/5 * * * * *")  //每5秒同步
    public void task() {

        List<String > ids = new ArrayList<>();
        Set<String> keys = redisTemplate.keys("rank:post:*");
        for (String key : keys) {

            if (redisUtil.hHasKey(key, "post:viewCount")) {
                String postId = key.substring("rank:post:".length());
                ids.add(postId);
            }
        }

        if (ids.isEmpty()) {
            return;
        }

        //须要更新的阅读量post
        List<Post> posts = postService.lambdaQuery().in(Post::getId, ids).list();
        for (Post post : posts) {
            Integer viewCount = (Integer) redisUtil.hget("rank:post:" + post.getId(), "post:viewCount");
            post.setViewCount(viewCount);
        }

        if (posts.isEmpty()) {
            return;
        }

        boolean isSuccess = postService.updateBatchById(posts);

        if (isSuccess) {
            for (String id : ids) {
                    redisUtil.hdel("rank:post:"+id,"post:viewCount");
                    logger.info(id+"------------>同步阅读量成功！");
            }
        }
    }
}
